package com.aa.activity;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import com.aa.Common;
import com.aa.R;
import com.aa.http.HttpOperation;


import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ShareActivity extends Activity implements OnClickListener{

	private String TAG = "ShareActivity";
	private final String mUrl = "http://121.9.64.196:8087/AAproject/api/mobile.php";
	private Button mbtnTitleOk;
	private TextView mtvTitleCenter;
	private Button mbtnChoosePhoneNumber;
	private EditText metSharePhoneNumber;
	private EditText metShareContent;
	private Button mbtnTitleBack;
	private String introMsg = "";
	private boolean isRegisetSMS = false;
	private int mSendSMSErrorCount = 0;
	private String mPhoneNumber = "";
	private Handler mHandler;
	private String mRetureErrMSG;
	private ProgressDialog mProgressDialog;
	private BroadcastReceiver smsRet = new BroadcastReceiver(){

			@Override
			public void onReceive(Context context, Intent intent) {
				
				
				Log.i(TAG, "getResultCode = " + getResultCode());
				switch (getResultCode()) {
				case -1:
					String str = getString(R.string.app_commend_7);
					Toast.makeText(ShareActivity.this, str, 3000).show();
					break;

				default:
					if(mSendSMSErrorCount == 1){
						
						mPhoneNumber = metSharePhoneNumber.getText().toString();
						introMsg = metShareContent.getText().toString();
						if (introMsg == null || introMsg.length() == 0) {
							introMsg = getString(R.string.invite_sms_conent);
						}
						sendSMSFromSystem();
					}else {
						mSendSMSErrorCount = 1;
					}
					
					
					break;
				}
				
			}
			  
		  };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mPhoneNumber = bundle.getString("PHONE");
		}
		initView();
		
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {				
				super.handleMessage(msg);
				
				switch (msg.what) {
				case 1:
					Toast.makeText(ShareActivity.this, R.string.app_share_3, 3000).show();
					break;
				case 0:
					Toast.makeText(ShareActivity.this, mRetureErrMSG, 3000).show();
					break;
				case 2:
					Toast.makeText(ShareActivity.this, R.string.http_get_fail, 3000).show();
					break;
				default:
					break;
				}
			}
			
		};
	}
	
	private void initView(){
		mbtnTitleOk = (Button)findViewById(R.id.btn_title);
		mbtnTitleOk.setText(R.string.app_ok);
		mbtnTitleOk.setVisibility(View.VISIBLE);
		mbtnTitleOk.setOnClickListener(this);
		
		mtvTitleCenter = (TextView)findViewById(R.id.tv_title_center);
		mtvTitleCenter.setText(R.string.app_share_1);
		mtvTitleCenter.setVisibility(View.VISIBLE);
		
		mbtnChoosePhoneNumber = (Button)findViewById(R.id.share_now_address);
		mbtnChoosePhoneNumber.setOnClickListener(this);
		
		metSharePhoneNumber = (EditText)findViewById(R.id.share_now_edit1);
		if (mPhoneNumber.length() > 0) {
			metSharePhoneNumber.setText(mPhoneNumber);
		}
		metShareContent = (EditText)findViewById(R.id.share_now_edit2);
		
		mbtnTitleBack = (Button)findViewById(R.id.btn_title_back);
		mbtnTitleBack.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.btn_title_back:
			finish();
			break;
		case R.id.share_now_address:
			Intent _Intent = new Intent("android.intent.action.PICK", ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(_Intent, 1);
			break;
		case R.id.btn_title:
			mPhoneNumber = metSharePhoneNumber.getText().toString();
			introMsg = metShareContent.getText().toString();
			if (introMsg == null || introMsg.length() == 0) {
				introMsg = getString(R.string.invite_sms_conent);
			}
			if (mPhoneNumber.length() == 0) {
				Toast.makeText(ShareActivity.this, R.string.commend_now_1, 3000).show();
				return;
			}
			sendSMS();
			sumbitShare();
			break;

		default:
			break;
		}
	}
	private void sendSMS(){
		
		
		Toast.makeText(ShareActivity.this, R.string.app_commend_11, 3000).show();
		
		SmsManager _SmsManager = SmsManager.getDefault();
		Intent _Intent = new Intent("SENT_SMS_ACTION");
		PendingIntent _PendingIntent = PendingIntent.getBroadcast(this, 0, _Intent, 0);
		
		Intent _Intent2 = new Intent("DELIVERED_SMS_ACTION");
		PendingIntent _PendingIntent2 = PendingIntent.getBroadcast(this, 0, _Intent2, 0);
		
		 registerReceiver(this.smsRet, new IntentFilter("SENT_SMS_ACTION"));
		 isRegisetSMS = true;
		 
		 Iterator _Iterator;
		 
		 if (introMsg.length() > 70) {
			_Iterator = _SmsManager.divideMessage(introMsg).iterator();
			while(true){
				if (!_Iterator.hasNext()) {
					return;
				}
				
				String str = getString(R.string.app_commend_11);
				Toast.makeText(getBaseContext(), str, 3000).show();
				_SmsManager.sendTextMessage(mPhoneNumber, null, (String)_Iterator.next(), _PendingIntent, _PendingIntent2);
			}
		}else {
			_SmsManager.sendTextMessage(mPhoneNumber, null, introMsg, _PendingIntent, _PendingIntent2);
		}
	}
	
	private void sendSMSFromSystem(){
		
	    Intent _Intent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:" + mPhoneNumber));
	    _Intent.putExtra("sms_body", introMsg);
	    startActivityForResult(_Intent, 2);
	  }
	
	private String getPhoneNumber2x(String contactId){
		
		String _Number = "";
		Cursor _Cursor = null;
		 _Cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = " + contactId, null, null);
		if (_Cursor.moveToFirst()) {
			_Number = _Cursor.getString(_Cursor.getColumnIndex("data1"));
			_Cursor.close();
			return _Number;
		}
		return _Number;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != RESULT_OK) {
			return;
		}
		
		if (requestCode == 1) {
			String contact_id = data.getData().getLastPathSegment();
			mPhoneNumber = getPhoneNumber2x(contact_id);
			metSharePhoneNumber.setText(mPhoneNumber);
		}		
		if (requestCode == 2) {
			mSendSMSErrorCount = 0;
		}
	}
	
	private void sumbitShare(){
		
		mProgressDialog = ProgressDialog.show(this, getString(R.string.app_progress_title), 
				getString(R.string.app_progress_tip),true,false);
		mProgressDialog.setCancelable(true);
	
	
	final JSONObject _SendJson = new JSONObject();
	JSONObject _BodyJson = new JSONObject();
	JSONObject _HeadJson = new JSONObject();
	try {
		_HeadJson.put("v", "1.0.0");
		_HeadJson.put("time", System.currentTimeMillis());
		_HeadJson.put("cmd", 17);
		_HeadJson.put("mac", Common.iMac);
		_HeadJson.put("agent", Common.iAgentId);
								
		_BodyJson.put("uid", Common.iUID);
		_BodyJson.put("pnumber", Common.iMyPhoneNumber);
		_BodyJson.put("friend", mPhoneNumber);
	
		
		_SendJson.put("head", _HeadJson);
		_SendJson.put("body", _BodyJson);
		Log.i(TAG, "sendJson = " + _SendJson);
	} catch (JSONException e) {
		
		e.printStackTrace();
	}
	
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			
			String _Result = HttpOperation.postRequestJSONFormat(mUrl, _SendJson.toString());
			mProgressDialog.dismiss();
			Log.i(TAG, "return _Result = " + _Result);
			if ( _Result == null || _Result.length() == 0 || _Result.equals(Common.iConnectOutTime)) {
				mHandler.sendEmptyMessage(2);
				return;
			}
			
				
				try {
					JSONObject _JsonObject = new JSONObject(_Result);
					
					JSONObject _Body = _JsonObject.getJSONObject("body");
					
					if(_Body.getInt("rcode") == 1) {
						mHandler.sendEmptyMessage(1);
					}else {
						mRetureErrMSG = _Body.getString("msg");
						mHandler.sendEmptyMessage(0);
					}
				} catch (JSONException e) {						
					e.printStackTrace();
				}
			}
			
		
	}).start();
}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 if ((smsRet != null) && (isRegisetSMS)){
			 
		      unregisterReceiver(smsRet);
		      isRegisetSMS = false;	     
		
		}
		   
	}
}
